package com.dopper.ws;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;

/**
 * description:
 * @author jincarry
 * @date 2019-07-10 8:42
 */
@Sharable
public class WebsocketMsgHandler extends SimpleChannelInboundHandler<WebSocketFrame> {

    private final static Logger log = LoggerFactory.getLogger(WebsocketMsgHandler.class);

    private Websocket websocket;

    WebsocketMsgHandler(Websocket websocket) {
        this.websocket = websocket;
    }

    void onOpen(Channel channel, Map<String, String> headers, Map<String, List<String>> params) {
        if (log.isDebugEnabled()) {
            log.debug("ws open: id={} headers={} params={}", channel.id(), headers, params);
        }
        websocket.onOpen(channel, headers, params);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame msg){
        if (msg instanceof CloseWebSocketFrame) {
            ctx.writeAndFlush(msg.retain()).addListener(ChannelFutureListener.CLOSE);
        }
        if (msg instanceof PingWebSocketFrame) {
            websocket.onPing(ctx.channel());
            return;
        }
        if (msg instanceof PongWebSocketFrame) {
            websocket.onPong(ctx.channel());
        }
        if (msg instanceof TextWebSocketFrame) {
            TextWebSocketFrame textWebSocketFrame = (TextWebSocketFrame) msg;
            websocket.onMsg(ctx.channel(), textWebSocketFrame.text());
            return;
        }
        if (msg instanceof BinaryWebSocketFrame) {
            BinaryWebSocketFrame frame = (BinaryWebSocketFrame) msg;
            byte[] bytes = new byte[frame.content().readableBytes()];
            frame.content().writeBytes(bytes);
            websocket.onMsg(ctx.channel(),bytes);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        websocket.onError(ctx.channel(), cause);
        super.exceptionCaught(ctx, cause);

        websocket.onClose(ctx.channel());
        ctx.channel().close();
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        websocket.onClose(ctx.channel());
        super.handlerRemoved(ctx);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent){
            IdleStateEvent event = (IdleStateEvent)evt;
            if (event.state() == IdleState.ALL_IDLE){
                ctx.channel().close();
            }
        }else {
            super.userEventTriggered(ctx,evt);
        }
    }
}
